from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from sqlalchemy import desc

from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import User, AdminLog
from applications.models import FinishedYPModel
from pinyin import pinyin
import datetime
bp = Blueprint('finished', __name__, url_prefix='/finished')


# 用户管理
@bp.get('/yp/')
@authorize("goodsfiles:finished:main:yp")
def main():

    return render_template('goodsfiles/finished/yp/main.html')


#   用户分页查询
@bp.get('/yp/data')
@authorize("goodsfiles:finished:main:yp")
def data():
    # 获取请求参数
    品名 = str_escape(request.args.get('品名', type=str))

    代码 = str_escape(request.args.get('代码', type=str))
    简拼 = str_escape(request.args.get('简拼', type=str))


    filters = []
    if 品名:
        filters.append(FinishedYPModel.品名.contains(品名))
    if 代码:
        filters.append(FinishedYPModel.代码.contains(代码))
    if 简拼:
        filters.append(FinishedYPModel.简拼.contains(简拼))

    query = db.session.query(
        FinishedYPModel
    ).filter(*filters).layui_paginate()

    return table_api(
        data=[{
            'id': item.id,
            '品名': item.品名,
            '简拼': item.简拼,
            '默认规格': item.默认规格,
            '默认产地': item.默认产地,
            '代码': item.代码,
            '执行标准': item.执行标准,
            '状态': item.状态,
            '版本号': item.版本号,


        } for item in query.items],
        count=query.total)

    # 用户增加


@bp.get('/yp/add')
@authorize("goodsfiles:finished:add:yp", log=True)
def add():
    roles = Role.query.all()
    return render_template('goodsfiles/finished/yp/add.html', roles=roles)


@bp.post('/yp/save')
@authorize("goodsfiles:finished:add:yp", log=True)
def save():
    req_json = request.get_json(force=True)

    row={

    '品名' : str_escape(req_json.get("品名")) , # 检验是否为空
    '默认规格' : str_escape(req_json.get("默认规格")) , # 检验是否为空
    '代码' : str_escape(req_json.get("代码")) , # 检验是否为空
    '状态' : str_escape(req_json.get("状态")) , # 检验是否为空
    '版本号' :  str_escape(req_json.get("版本号"))  , # 检验是否为空
    '默认产地' : str_escape(req_json.get("默认产地")) , # 检验是否为空
    '归属类别' : str_escape(req_json.get("归属类别")) , # 检验是否为空
    '执行标准' : str_escape(req_json.get("执行标准")) if str_escape(req_json.get("执行标准")) else '',  # 检验是否为空
    '检验标准' : str_escape(req_json.get("检验标准")),  # 检验是否为空
        '工艺验证': str_escape(req_json.get("工艺验证")),  # 检验是否为空
    '贮存条件': str_escape(req_json.get("贮存条件")),
        '药典贮存条件': str_escape(req_json.get("药典贮存条件")),
        '备注': str_escape(req_json.get("备注")),
        '性味与归经': str_escape(req_json.get("性味与归经")),
        '功能与主治': str_escape(req_json.get("功能与主治")),
        '用法与用量': str_escape(req_json.get("用法与用量")),
        '注意事项': str_escape(req_json.get("注意事项")),
        '拉丁文': str_escape(req_json.get("拉丁文")),
        '采收时间': str_escape(req_json.get("采收时间")),
        '初加工方法': str_escape(req_json.get("初加工方法")),
        '质量要求': str_escape(req_json.get("质量要求")),
        '保质期': str_escape(req_json.get("保质期")),
        '安全库存天数': str_escape(req_json.get("安全库存天数")),
        '自定义安全库存': str_escape(req_json.get("自定义安全库存")),
        '养护内容': str_escape(req_json.get("养护内容")),
        '税率': str_escape(req_json.get("税率")),



    }
    for k,v in row.items():
        if k in ['品名','代码','执行标准']:

            if not v:
                return fail_api(msg=f"{k}不得为空")
    row['简拼']=pinyin.get_initial(row['品名'],"").upper()
    row['全拼'] =pinyin.get(row['品名'], format='strip').upper()
    try:
        pro=FinishedYPModel(**row)
        db.session.add(pro)

        db.session.commit()

    except Exception as e:
        print(e)
        return fail_api(msg=f"发生错误")
    return success_api(msg="增加成功")


# 删除用户
@bp.delete('/yp/remove/<int:id>')
@authorize("goodsfiles:finished:remove:yp", log=True)
def delete(id):

    res = FinishedYPModel.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


#  编辑用户
@bp.get('/yp/edit/<int:id>')
@authorize("goodsfiles:finished:edit:yp", log=True)
def edit(id):
    raw_info = curd.get_one_by_id(FinishedYPModel, id)


    return render_template('goodsfiles/finished/yp/edit.html', info=raw_info)


#  编辑用户
@bp.put('/yp/update')
@authorize("goodsfiles:finished:edit:yp", log=True)
def update():
    req_json = request.get_json(force=True)
    id = str_escape(req_json.get("id"))
    # username = str_escape(req_json.get('username'))
    # real_name = str_escape(req_json.get('realName'))
    # dept_id = str_escape(req_json.get('deptId'))
    row = {

        '品名': str_escape(req_json.get("品名")),  # 检验是否为空
        '默认规格': str_escape(req_json.get("默认规格")),  # 检验是否为空
        '代码': str_escape(req_json.get("代码")),  # 检验是否为空
        '状态': str_escape(req_json.get("状态")),  # 检验是否为空
        '版本号': str_escape(req_json.get("版本号")),  # 检验是否为空
        '默认产地': str_escape(req_json.get("默认产地")),  # 检验是否为空
        '归属类别': str_escape(req_json.get("归属类别")),  # 检验是否为空
        '执行标准': str_escape(req_json.get("执行标准")) if str_escape(req_json.get("执行标准")) else '',  # 检验是否为空
        '检验标准': str_escape(req_json.get("检验标准")),  # 检验是否为空
        '工艺验证': str_escape(req_json.get("工艺验证")),  # 检验是否为空
        '贮存条件': str_escape(req_json.get("贮存条件")),
        '药典贮存条件': str_escape(req_json.get("药典贮存条件")),
        '备注': str_escape(req_json.get("备注")),
        '性味与归经': str_escape(req_json.get("性味与归经")),
        '功能与主治': str_escape(req_json.get("功能与主治")),
        '用法与用量': str_escape(req_json.get("用法与用量")),
        '注意事项': str_escape(req_json.get("注意事项")),
        '拉丁文': str_escape(req_json.get("拉丁文")),
        '采收时间': str_escape(req_json.get("采收时间")),
        '初加工方法': str_escape(req_json.get("初加工方法")),
        '质量要求': str_escape(req_json.get("质量要求")),
        '保质期': str_escape(req_json.get("保质期")),
        '安全库存天数': str_escape(req_json.get("安全库存天数")),
        '自定义安全库存': str_escape(req_json.get("自定义安全库存")),
        '养护内容': str_escape(req_json.get("养护内容")),
        '税率': str_escape(req_json.get("税率")),

    }
    for k, v in row.items():
        if k in ['品名', '代码', '执行标准']:

            if not v:
                return fail_api(msg=f"{k}不得为空")
    row['简拼'] = pinyin.get_initial(row['品名'], "").upper()
    row['全拼'] = pinyin.get(row['品名'], format='strip').upper()
    row['update_at'] =datetime.datetime.now()

    try:
        query=FinishedYPModel.query.filter_by(id=id).update(row)
        db.session.commit()
    except:
        return fail_api(msg="更新失败,可能是格式错误")
    if not query:
        return fail_api(msg="更新失败")
    return success_api(msg="更新成功")

# 启用字典数据
@bp.put('/yp/enable')
@authorize("goodsfiles:finished:edit:yp", log=True)
def dict_data_enable():
    _id = request.get_json(force=True).get('dataId')
    if _id:
        res = curd.enable_status(model=FinishedYPModel, id=_id,filed='状态')
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用字典数据
@bp.put('/yp/disable')
@authorize("goodsfiles:finished:edit:yp", log=True)
def dict_data_disenable():
    _id = request.get_json(force=True).get('dataId')
    if _id:
        res = curd.disable_status(model=FinishedYPModel, id=_id,filed='状态')
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")

